package com.yh.concert.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.ImageUtils;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.sun.org.apache.xpath.internal.operations.Bool;
import com.yh.concert.domain.YhConcert;
import com.yh.concert.domain.YhMerchart;
import com.yh.concert.domain.YhSite;
import com.yh.concert.domain.dto.ConcertDto;
import com.yh.concert.domain.dto.FIleDto;
import com.yh.concert.domain.dto.OrderDto;
import com.yh.concert.service.IYhConcertService;
import com.yh.concert.service.IYhMerchartService;
import com.yh.concert.service.IYhSiteService;
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.yh.concert.domain.YhOrder;
import com.yh.concert.service.IYhOrderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 订单管理Controller
 *
 * @author yh
 * @date 2025-02-26
 */
@Api(tags="订单管理管理")
@RestController
@RequestMapping("/concert/order")
public class YhOrderController extends BaseController
{
    @Autowired
    private IYhOrderService yhOrderService;

    @Autowired
    private IYhConcertService yhConcertService;

    @Autowired
    private IYhMerchartService merChartService;

    @Autowired
    private IYhSiteService yhSiteService;



    //设置APPID/AK/SK
    public static final String APP_ID = "117743378";
    public static final String API_KEY = "4i8KIimLC4jKczNPdin9xxZy";
    public static final String SECRET_KEY = "mZkMil6wMAqCG7zNCPxREJoHx55aQB8U";
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;


    /**
     * 查询订单管理列表
     */
    @Anonymous
    @ApiOperation("查询订单管理列表")
    @PreAuthorize("@ss.hasPermi('concert:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(YhOrder yhOrder)
    {
        startPage();

        // 根据用户权限获取订单
        LoginUser loginUser = getLoginUser();
        if (loginUser.getUserId() == 1 || loginUser.getUserId() == 107){
            yhOrder.setUserId(null);
        }else {
            // 查询是否是商家
            // 获取用户权限
            if (sysUserRoleMapper.isMerchart(loginUser.getUserId())  == 1){
                logger.info("loginUser={}",loginUser.getUser());
                YhMerchart one = merChartService.getOne(new LambdaQueryWrapper<YhMerchart>().eq(YhMerchart::getUserId, loginUser.getUser().getUserId()));
                if (BeanUtil.isNotEmpty(one)){
                    yhOrder.setMerchartId(one.getId());
                }else {
                    throw new RuntimeException("未获取到商家信息");
                }
            }else {
                yhOrder.setUserId(loginUser.getUserId());
            }
        }
        List<YhOrder> list = yhOrderService.selectYhOrderList(yhOrder);

        List<OrderDto> orders = new ArrayList<>();
        for (YhOrder yhOrder1 : list) {
            // 获取用户、商户、演唱会名信息
            SysUser sysUser = sysUserMapper.selectUserById(yhOrder1.getUserId());
            YhMerchart merchart = merChartService.getOne(new LambdaQueryWrapper<YhMerchart>().eq(YhMerchart::getId, yhOrder1.getMerchartId()));
            YhSite site = yhSiteService.getOne(new LambdaQueryWrapper<YhSite>().eq(YhSite::getId, yhOrder1.getSiteId()));
            YhConcert concert = yhConcertService.getById(yhOrder1.getConcertId());
            OrderDto orderDto = new OrderDto();
            BeanUtil.copyProperties(yhOrder1,orderDto);
            orderDto.setConcert(concert.getConcertName());
            orderDto.setSite(site.getSiteName());
            orderDto.setMerchart(merchart.getMerchartName());
            orderDto.setUserName(sysUser.getUserName());
            orders.add(orderDto);
        }

        return getDataTable(orders);
    }

    /**
     * 导出订单管理列表
     */
    @ApiOperation("导出订单管理列表")
    @PreAuthorize("@ss.hasPermi('concert:order:export')")
    @Log(title = "订单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, YhOrder yhOrder)
    {

        List<YhOrder> list = yhOrderService.selectYhOrderList(yhOrder);
        ExcelUtil<YhOrder> util = new ExcelUtil<YhOrder>(YhOrder.class);
        util.exportExcel(response, list, "订单管理数据");
    }

    /**
     * 获取订单管理详细信息
     */
    @Anonymous
    @ApiOperation("获取订单管理详细信息")
    @PreAuthorize("@ss.hasPermi('concert:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(yhOrderService.getById(id));
    }

    /**
     * 新增订单管理
     */
    @ApiOperation("新增订单管理")
    @PreAuthorize("@ss.hasPermi('concert:order:add')")
    @Log(title = "订单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody YhOrder yhOrder)
    {
        LoginUser loginUser = getLoginUser();
        // 查询数据库中是否已经有了该演唱会的订单
        YhOrder one = yhOrderService.getOne(new LambdaQueryWrapper<YhOrder>().eq(YhOrder::getConcertId, yhOrder.getMerchartId()).eq(YhOrder::getUserId, yhOrder.getUserId()));
        if (BeanUtil.isNotEmpty(one)){
            return AjaxResult.error("该演唱会已报名");
        }
        return toAjax(yhOrderService.save(yhOrder));
    }

    /**
     * 修改订单管理
     */
    @ApiOperation("修改订单管理")
    @PreAuthorize("@ss.hasPermi('concert:order:edit')")
    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YhOrder yhOrder)
    {
        return toAjax(yhOrderService.updateById(yhOrder));
    }

    /**
     * 删除订单管理
     */
    @ApiOperation("删除订单管理")
    @PreAuthorize("@ss.hasPermi('concert:order:remove')")
    @Log(title = "订单管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(yhOrderService.removeByIds(Arrays.asList(ids)));
    }


    /**
     * 用户下单
     */

    @ApiOperation("用户下单")
    @PostMapping("/addOrder")
    public AjaxResult addOrder(@RequestBody YhConcert concert)
    {

        logger.info("用户下单=>{}", concert);
        // 查询用户是否已经下单
        LoginUser loginUser = getLoginUser();
        if (BeanUtil.isNotEmpty(yhOrderService.getOne(new LambdaQueryWrapper<YhOrder>().eq(YhOrder::getUserId, loginUser.getUserId()).eq(YhOrder::getConcertId, concert.getId())))){
            return AjaxResult.error("您已经报名了");
        }
        // 查询已报名人数
        LambdaQueryWrapper<YhOrder> yhOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        yhOrderLambdaQueryWrapper.eq(YhOrder::getConcertId,concert.getId());
        yhOrderLambdaQueryWrapper.eq(YhOrder::getStatus,0L);
        long count = yhOrderService.count(yhOrderLambdaQueryWrapper);
        if (concert.getCount() - count > 1){
            // 直接插入
            YhOrder yhOrder = new YhOrder();
            yhOrder.setUserId(loginUser.getUserId());
            yhOrder.setMerchartId(concert.getMerchartId());
            yhOrder.setSiteId(Long.valueOf(concert.getAddress()));
            yhOrder.setConcertId(concert.getId());

            yhOrder.setStatus(0L);
            logger.info("用户下单=>{}", yhOrder);
            yhOrderService.save(yhOrder);
        }else if (concert.getCount() - count == 1){
            // 修改演唱会状态status为2
            LambdaUpdateWrapper<YhConcert> yhConcertLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            yhConcertLambdaUpdateWrapper.eq(YhConcert::getId,concert.getId());
            yhConcertLambdaUpdateWrapper.set(YhConcert::getStatus,2L);
            yhConcertService.update(yhConcertLambdaUpdateWrapper);

            // 插入数据
            YhOrder yhOrder = new YhOrder();
            yhOrder.setUserId(getUserId());
            yhOrder.setMerchartId(concert.getMerchartId());
            yhOrder.setSiteId(Long.valueOf(concert.getAddress()));
            yhOrder.setConcertId(concert.getId());
            yhOrder.setStatus(0L);
            logger.info("用户下单=>{}", yhOrder);

            yhOrderService.save(yhOrder);
        }else {
            return AjaxResult.error("人数已满");
        }

        return AjaxResult.success("下单成功");
    }

    /**
     * 接受前端传入的base64图片，返回图片的url地址
     */
    @ApiOperation("接受前端传入的base64图片，返回图片的url地址")
    @PostMapping("/uploadFile/{userId}/{orderId}")
    public AjaxResult upload(@PathVariable Long userId, @PathVariable Long orderId, MultipartFile file) throws IOException {

        // 读取本地图片并转化为base64
        //
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        String avatar = sysUser.getAvatar();

        // 本地资源路径
        String localPath = RuoYiConfig.getProfile();
        // 数据库资源地址
        String downloadPath = localPath + StringUtils.substringAfter(avatar, Constants.RESOURCE_PREFIX);
        // 过滤avatar中/profile/后的字符串

        File fileUser = new File(downloadPath);
        if (!fileUser.exists() || !fileUser.canRead()) {
            logger.error("文件不存在或无法读取: {}", downloadPath);
            return AjaxResult.error("文件不存在或无法读取");
        }

        // 将file读取的图片转化为base64
        byte[] bytes = FileUtils.readFileToByteArray(fileUser);
        String base64User = Base64Utils.encodeToString(bytes);

        // 将前端传入的file转化为base64
        byte[] bytesFile = file.getBytes();
        String base64File = Base64Utils.encodeToString(bytesFile);


        MatchRequest req1 = new MatchRequest(base64File, "BASE64");
        MatchRequest req2 = new MatchRequest(base64User, "BASE64");
        ArrayList<MatchRequest> requests = new ArrayList<MatchRequest>();
        requests.add(req1);
        requests.add(req2);
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);

        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        JSONObject res = client.match(requests);
        System.out.println(res.toString(2));
        // 查看res中的error_msg是否为SUCCESS
        if (res.getString("error_msg").equals("SUCCESS")) {
            // 获取人脸识别结果
            JSONObject result = res.getJSONObject("result");
            int score = result.getInt("score");
            if (score > 80) {
                LambdaUpdateWrapper<YhOrder> yhOrderLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                yhOrderLambdaUpdateWrapper.eq(YhOrder::getId, orderId);
                yhOrderLambdaUpdateWrapper.set(YhOrder::getStatus, 1L);
                yhOrderService.update(yhOrderLambdaUpdateWrapper);
                return AjaxResult.success("人脸识别成功");
            }
        }else{
            return AjaxResult.error("人脸识别失败! "+res.getString("error_msg"));
        }
        return AjaxResult.error("人脸识别失败,比对未成功");
    }
}
